package divestoclimb.checklist;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;

import divestoclimb.checklist.storage.DbAdapter;
import divestoclimb.checklist.storage.XmlAdapter;

import android.os.Bundle;

/**
 * An Activity that restores all checklists and templates in the default
 * locations to the internal database.
 * @author Ben Roberts (divestoclimb@gmail.com)
 *
 */
public class Restore extends AbsBackupRestore {

	private DbAdapter mDbHelper;
	private XmlAdapter mXmlHelper;
	private File[] mTemplates, mChecklists;
	private Integer mTemplateCount, mChecklistCount;
	
	/**
	 * A FilenameFilter that returns only items which match a given extension.
	 * @author Ben Roberts (divestoclimb@gmail.com)
	 */
	private class ExtensionMatcher implements FilenameFilter {
		private String mExtension;
		public ExtensionMatcher(String ext) {
			mExtension = ext;
		}
		public boolean accept(File dir, String filename) {
			String ext = filename.substring(filename.lastIndexOf(".")+1);
			return ext.equals(mExtension);
		}
	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		mDbHelper = new DbAdapter(this);
		mXmlHelper = new XmlAdapter(mDbHelper);
	}

	@Override
	public void onResume() {
		mDbHelper.open();
		mTemplates = D2cChecklist.TEMPLATE_DEFAULT_LOCATION.listFiles(
				new ExtensionMatcher(D2cChecklist.TEMPLATE_EXTENSION));
		mChecklists = D2cChecklist.CHECKLIST_DEFAULT_LOCATION.listFiles(
				new ExtensionMatcher(D2cChecklist.CHECKLIST_EXTENSION));
		mTemplateCount = -1;
		mChecklistCount = -1;
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		mDbHelper.close();
	}

	@Override
	protected int getItemCount() {
		return mTemplates.length + mChecklists.length;
	}

	@Override
	protected String getNextItem() {
		if(++mTemplateCount < mTemplates.length) {
			return mTemplates[mTemplateCount].getName();
		} else if(++mChecklistCount < mChecklists.length) {
			return mChecklists[mChecklistCount].getName();
		} else {
			return null;
		}
	}

	@Override
	protected boolean processItem() {
		try {
			if(mTemplateCount < mTemplates.length) {
				FileReader buffer = new FileReader(mTemplates[mTemplateCount]);
				return mXmlHelper.readTemplate(buffer, true) != -1;
			} else {
				FileReader buffer = new FileReader(mChecklists[mChecklistCount]);
				return mXmlHelper.readChecklist(buffer, true) != -1;
			}
		} catch(FileNotFoundException e) {
			return false;
		}
	}
}